<template>
  <div class="page-root">
    <!-- 头部导航 -->
    <div class="nav-header">
      <BaseButton @click="handleBack">
        <ChevronsLeft class="icon-base" />
      </BaseButton>
      <h1 class="header-title">常用地址</h1>
      <BaseButton @click="handleAddNew">
        <PlusSquare class="icon-base" />
      </BaseButton>
    </div>

    <!-- 地址列表 -->
    <div class="address-list">
      <div v-for="pair in sortedAddresses" :key="pair.id" class="address-card">
        <div class="card-body">
          <div class="info-left">
            <div class="address-row">
              <div class="address-dot dot-start"></div>
              <span class="address-text">{{ pair.from }}</span>
            </div>
            <div class="address-row">
              <div class="address-dot dot-end"></div>
              <span class="address-text">{{ pair.to }}</span>
            </div>
            <div class="phone-text">
              联系电话: {{ pair.phone }}
            </div>
          </div>
          <div class="info-right">
            <span v-if="pair.isPrimary" class="primary-badge">主地址</span>
            <BaseButton 
              @click.stop="toggleMenu(pair.id)"
            >
              <MoreHorizontal class="icon-base" />
            </BaseButton>
          </div>
        </div>
        <!-- 下拉菜单 -->
        <DropdownMenu 
          :visible="openMenuId === pair.id"
          :menuRef="el => { if (el) menuRefs[pair.id] = el }"
        >
          <BaseButton @click="handleEdit(pair.id)" class="menu-item">
            <PenTool class="icon-base" />
            <span>编辑</span>
          </BaseButton>
          <BaseButton @click="handleDelete(pair.id)" class="menu-item">
            <Trash class="icon-base" />
            <span>删除</span>
          </BaseButton>
        </DropdownMenu>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router';
import { 
  ChevronsLeft, 
  PlusSquare, 
  PenTool, 
  Trash, 
  MoreHorizontal 
} from 'lucide-vue-next'
import router from '@/router'
import axios from 'axios'
import BaseButton from '@/components/BaseButton.vue'
import DropdownMenu from '@/components/DropdownMenu.vue'

const components = { BaseButton, DropdownMenu }

const addressPairs = ref([])

const openMenuId = ref(null)
const menuPosition = ref({ top: 0, left: 0 })

// 添加缺少的状态变量
const isEditing = ref(false)
const editingAddress = ref(null)

// 添加ref用于菜单引用
const menuRefs = ref({})

const handleBack = () => {
  router.push({
    path: '/edit',
  })
}

const handleAddNew = () => {
  router.push({
    path: '/edit/address/update',
    query: { mode: 'new' }
  })
}

const handleEdit = (id) => {
  const address = addressPairs.value.find(addr => addr.id === id)
  if (address) {
    router.push({
      path: '/edit/address/update',
      query: { 
        mode: 'edit',
        id: address.id,
        from: address.from,
        to: address.to,
        phone: address.phone,
        isPrimary: address.isPrimary ? '1' : '0'
      }
    })
  }
}

const handleDelete = async (id) => {
  try {
    console.log('准备删除地址, ID:', id);
    const currentUser = JSON.parse(localStorage.getItem('user'));
    const userId = currentUser ? currentUser.uid : null;

    if (!userId) {
      alert('未找到用户信息，请重新登录');
      return;
    }

    const response = await axios.delete('/api/auth/addresses', {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': localStorage.getItem('token')
      },
      data: {
        uid: userId,
        address_id: id
      }
    });

    if (response.data.code === 0) {
      alert('删除地址成功');
      await loadAddresses(); // 重新加载地址列表
      openMenuId.value = null; // 关闭操作菜单
    } else {
      throw new Error(response.data.message || '删除失败');
    }
  } catch (error) {
    console.error('删除地址失败:', error);
    alert(error.response?.data?.message || error.message || '删除失败');
  }
}

// 修改保存方法
const handleSave = async (formData) => {
  try {
    console.log('准备保存的表单数据:', formData)
    const currentUser = JSON.parse(localStorage.getItem('user'));
    const userId = currentUser ? currentUser.uid : null;

    if (!userId) {
      console.error('未找到用户ID');
      return false;
    }

    const data = {
      uid: userId,
      address_id: editingAddress.value?.id || 0,
      pickup_address: formData.from,
      delivery_address: formData.to,
      is_primary: formData.isPrimary,
      phone_number: formData.phone
    }
    
    const response = await axios.put('/api/auth/addresses', 
      data,
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': localStorage.getItem('token')
        }
      }
    );

    if (response.data.code === 0) {
      // 重新加载地址列表
      await loadAddresses()
      // 重置状态
      isEditing.value = false
      editingAddress.value = null
      console.log('保存成功')
      return true
    }
    
    throw new Error(response.data.message || '保存失败');

  } catch (error) {
    console.error('保存地址失败:', error.response?.data?.message || error.message)
    return false
  }
}

// 点击外部关闭菜单
const handleClickOutside = (event) => {
  console.log('handleClickOutside triggered');
  console.log('Event target:', event.target);

  if (openMenuId.value !== null) {
    const menuElement = menuRefs.value[openMenuId.value]
    const targetElement = event.target
    
    // 检查点击是否在菜单外部和更多按钮外部
    if (menuElement && 
        !menuElement.contains(targetElement) && 
        !targetElement.closest('.base-btn')) {
      openMenuId.value = null
    }
  }
}

// 修改 toggleMenu 方法
const toggleMenu = (id) => {
  openMenuId.value = openMenuId.value === id ? null : id
}

// 修改数据加载方法
const loadAddresses = async () => {
  try {
    console.log('开始加载地址列表...')
    const currentUser = JSON.parse(localStorage.getItem('user'));
    const userId = currentUser ? currentUser.uid : null;

    if (!userId) {
      console.error('未找到用户ID');
      return;
    }

    const response = await axios.get('/api/auth/addresses', {
      params: { uid: userId },
      headers: {
        'Content-Type': 'application/json',
        'Authorization': localStorage.getItem('token')
      }
    });

    console.log('API响应状态:', response.data.code);
    console.log('API响应消息:', response.data.message);

    let addresses = [];
    if (response.data.code === 0 && response.data.data?.addresses) {
      console.log('地址数组数据:', response.data.data.addresses);
      
      addresses = response.data.data.addresses.map(addr => ({
        id: addr.AddressID,
        from: addr.PickupAddress,
        to: addr.DeliveryAddress,
        phone: addr.PhoneNumber,
        isPrimary: addr.IsPrimary == 1
      }));
    }

    console.log('处理后的地址数据:', addresses);
    addressPairs.value = addresses;

  } catch (error) {
    console.error('获取地址列表失败:', error);
    addressPairs.value = []; // 确保失败时设置为空数组
  }
};

const sortedAddresses = computed(() => {
  return addressPairs.value.slice().sort((a, b) => {
    return b.isPrimary - a.isPrimary;
  });
});

// 在组件挂载时加载数据
onMounted(() => {
  loadAddresses()
  // 添加点击事件监听
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  // 移除点击事件监听
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>

span{
  color: #000000;
}
/* 基础布局 */
.page-root {
  padding: 1rem;
  background: #f8f9fa;
  min-height: 100vh;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.nav-btn {
  padding: 0.5rem;
  border: none;
  background: transparent;
  border-radius: var(--border-radius-small);
}

.nav-btn:hover {
  background-color: #f3f4f6;
}

.nav-btn:focus {
  outline: none;
}

.header-title {
  /* 原先 font-size: 1.125rem; */
  font-size: var(--font-size-large);
  font-weight: 500;
  color: #000;
}

/* 列表容器 */
.address-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  max-height: calc(100vh - 6rem); /* 添加最大高度 */
  overflow-y: auto; /* 修改为 auto */
  padding: 0 0.5rem;
  border-top: 1px solid #e5e7eb;
}

/* 地址卡片 */
.address-card {
  position: relative;
  background: white;
  padding: 1.25rem;  /* 增加内边距，原来是 0.75rem */
  border-bottom: 1px solid #e5e7eb;
  border-radius: var(--border-radius-small);
  box-shadow: none;
  transition: box-shadow 0.3s ease;
}

.address-card:hover {
  background-color: #fafafa;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.card-body {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.info-left {
  display: flex;
  flex-direction: column;
  flex: 1;
  margin-right: 0.5rem;
}

.info-right {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  justify-content: center;
}

/* 下拉菜单 */
.dropdown-menu {
  position: absolute;
  right: 0.5rem;
  top: 2.5rem;
  background: white;
  border-radius: var(--border-radius-small);
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
  z-index: 50;
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;  /* 添加间距 */
  width: 100%;
  padding: 0.5rem 1rem;
  border: none;
  background: transparent;
  border-radius: var(--border-radius-small);
  cursor: pointer;
}

.menu-item .icon-base {
  width: 1rem;
  height: 1rem;
  color: #000000 !important;  /* 确保图标颜色 */
  stroke: #000000;  /* 确保图标描边 */
}

.menu-item:hover {
  background-color: #f3f4f6;
}

/* 地址信息布局 */
.address-row {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.75rem;  /* 增加底部间距，原来是 0.375rem */
}

.address-dot {
  width: 0.375rem;
  height: 0.375rem;
  border-radius: 9999px;
}

.dot-start {
  background-color: #3b82f6;
}

.dot-end {
  background-color: #10b981;
}

.address-text {
  /* 原先 font-size: 0.875rem; */
  font-size: var(--font-size-normal);
  color: #1f2937;
}

.primary-badge {
  /* 原先 font-size: 0.75rem; */
  font-size: var(--font-size-small);
  color: #3b82f6;
  border: 1px solid #3b82f6;
  border-radius: var(--border-radius-small);
  padding: 0 0.25rem;
}

.phone-text {
  font-size: var(--font-size-small);
  color: #6b7280;
  margin-left: 1rem;
  margin-top: 0.5rem;  /* 增加顶部间距 */
}

/* 添加统一的图标样式 */
.icon-base {
  width: 1.5rem;
  height: 1.5rem;
  color: #000000 ;
  stroke: currentColor;
  stroke-width: 2;
}

.menu-item .icon-base {
  width: 1rem;
  height: 1rem;
}

/* 确保图标容器样式正确 */
.nav-btn, .more-btn, .menu-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 移除之前的 icon 相关样式 */
</style>
